﻿using System;
using System.Threading;
using System.Globalization;
using RapidSpider.DownloadAgents;

namespace RapidSpider.ApplicationControllers
{
	public partial class Controller
    {
        #region Methods
        public static Thread GetThread(IDownloadAgent theInstance)
        {
            for (int i = 0; i < Controller.Threads.Count; i++)
            {
                if (Controller.Threads[i].Name.Equals(
                    theInstance.GetHashCode().ToString(
                        CultureInfo.CurrentCulture)))
                {
                    return Controller.Threads[i];
                }
            }
            return null;
        }
    
        public static void AbortAndRemoveThread(IDownloadAgent theInstance)
        {
            for (int i = 0; i < Controller.Threads.Count; i++)
            {
                if (Controller.Threads[i].Name.Equals(
                    theInstance.GetHashCode().ToString(
                        CultureInfo.CurrentCulture)))
                {
                    try
                    {
                        Controller.Threads.RemoveAt(i);
                    }
                    catch (ArgumentOutOfRangeException) { }
                    break;
                }
            }
        }

        public static void AbortAndRemoveAllThreads()
        {
            for (int i = 0; i < Controller.Threads.Count; i++)
            {
                try
                {
                    Controller.Threads[i].Abort();
                    // Raises a ThreadAbortException in the thread on which it is 
                    // invoked, to begin the process of terminating the thread. 
                    // Calling this method usually terminates the thread.
                }
                catch (ThreadAbortException) { }
            }
            Controller.Threads.Clear();
        }
        #endregion
    }
}
